package patrol.mobile.com.mobilepatrol;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Process;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.orhanobut.logger.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.realm.DynamicRealm;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmMigration;
import io.realm.RealmSchema;
import io.rong.imkit.RongIM;
import okhttp3.OkHttpClient;
import patrol.mobile.com.mobilepatrol.utils.BitmapFillet;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.RoundBitmapDisplayer;
import patrol.mobile.com.mobilepatrol.utils.StringUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;

/**
 * Created by apple on 17/9/27.
 */

public class PatrolApp extends Application {
    public static Context context;
    public static Realm realm;

    private int width;
    private int height;
    public static ImageLoader mImageLoader = null;
    private static DisplayImageOptions mOptionsCircle;
    private static DisplayImageOptions mOptionsRound = null;

    private String serverHost;
    public static final String SERVER_HOST = "server_host";

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        init();
        if (shouldInit()) {
            MiPushClient.registerPush(this, "2882303761517861129", "5561786142129");
        }
        RongIM.init(this);
        LocationHelper.init(this);
    }

    private void init() {

        initHTTP();
        initRealm();
        ToastUtils.init(context);
        initImageLoader();
        Logger.init("SHJ--");
    }

    private void initRealm() {
        Realm.init(this);
        RealmConfiguration configuration = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .migration(new Migration()) // Migration to run instead of throwing an exception
                .build();
        Realm.setDefaultConfiguration(configuration);
        realm = Realm.getDefaultInstance();
    }

    private void initHTTP() {
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor("SHJ--"))
                .connectTimeout(100000L, TimeUnit.MILLISECONDS)
                .readTimeout(100000L, TimeUnit.MILLISECONDS)
                //其他配置
                .cookieJar(cookieJar)
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }

    private void initImageLoader() {
        width = getResources().getDisplayMetrics().widthPixels;
        height = getResources().getDisplayMetrics().heightPixels;

        /** 使用默认的配置 by : KNothing*/
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(width, height).threadPoolSize(3)
                .build();
        mImageLoader = ImageLoader.getInstance();
        mImageLoader.init(configuration);
        mOptionsCircle = new DisplayImageOptions.Builder()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageForEmptyUri(R.mipmap.ic_nav_picture)
                .showImageOnFail(R.mipmap.ic_nav_picture)
                .showImageOnLoading(R.mipmap.ic_nav_picture)
                .cacheOnDisc(true)
                .cacheInMemory(true)
                .displayer(new RoundBitmapDisplayer(BitmapFillet.ROUND, 0))
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .build();
        mOptionsRound = new DisplayImageOptions.Builder()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageForEmptyUri(R.mipmap.logo)
                .showImageOnFail(R.mipmap.ic_nav_picture)
                .showImageOnLoading(R.mipmap.ic_nav_picture)
                .cacheOnDisc(true)
                .cacheInMemory(true)
                .displayer(new RoundBitmapDisplayer(BitmapFillet.ALL, CommonUtil.dip2px(this, 6)))
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .build();
    }

    /*显示圆形头像*/
    public static void displayCircleImage(ImageView avatarView, String avatarUrl) {
        display(avatarView, avatarUrl, mOptionsCircle, null, null);
    }

    public static void displayRoundImage(ImageView avatarView, String avatarUrl) {
        display(avatarView, avatarUrl, mOptionsRound, null, null);
    }

    public static void displayRoundImage(ImageView avatarView, String avatarUrl, ImageLoadingListener listener) {
        display(avatarView, avatarUrl, mOptionsRound, listener, null);
    }

    public static void display(ImageView avatarView, String avatarUrl, DisplayImageOptions options, ImageLoadingListener listener, ImageSize size) {
        if (avatarUrl == null) {
            avatarUrl = "";
        }
        if (size == null) {
            mImageLoader.displayImage(avatarUrl, avatarView, options, listener);
        } else {
            mImageLoader.displayImage(avatarUrl, new ImageViewAware(avatarView), options, size, null, null);
        }
    }

    public String getServerHost() {
        if (StringUtils.isEmpty(serverHost)) {
            serverHost = getProperty(SERVER_HOST);
            if (StringUtils.isEmpty(serverHost))
                serverHost = getString(R.string.url_server_host);
        }

        return serverHost;
    }

    public String getProperty(String key) {
        return AppConfig.getAppConfig(this).get(key);
    }

    /**
     * 获取App安装包信息
     *
     * @return
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null) info = new PackageInfo();
        return info;
    }

    /**
     * 获取App唯一标识
     *
     * @return
     */
    public String getAppId() {
        String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
        if (StringUtils.isEmpty(uniqueID)) {
            uniqueID = UUID.randomUUID().toString();
            setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
        }
        return uniqueID;
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public class Migration implements RealmMigration {

        @Override
        public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
            RealmSchema schema = realm.getSchema();
            Log.e("~~~~~", oldVersion + "_____" + newVersion);
        }
    }

    //todo 分包未添加
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

}
